<?php

require 'image_functions.php';
$jpeg_quality    = isset($env['image']['jpeg_quality']) ? $env['image']['jpeg_quality'] : 60;
$png_compression = isset($env['image']['png_compression']) ? $env['image']['png_compression'] : 5;
$max_dimension   = isset($env['image']['max_dimension']) ? $env['image']['max_dimension'] : false;

array_pop($path); // discard filename

$cache_file      = $app_root . $site['home_dir'] . "/cache/images/". str_replace(':', '_', join('/', array_slice($path,1)));

$image_id = array_pop($path);
if (ctype_digit($image_id)) {
	
	$image = $db->fetchRow("SELECT * FROM cms_images WHERE id=? AND site_id=?", array($image_id, $site['id']));
	if (!in_array($image['mime_type'], array('image/jpeg', 'image/gif', 'image/png'))) {
		$image['mime_type'] = 'image/jpeg';
	}
	if (file_exists($cache_file)) {
		header("Content-type: {$image['mime_type']}");
		header("Content-disposition: inline; filename={$image['filename']}");
		readfile($cache_file);
		exit;
	} else {
		
		$gd = imagecreatefromstring($image['data']);

		$commands = array_slice($path, 1);
		foreach($commands as $command) {
			$command = split(':', $command);
			if ($command[0] == 'rc' and ctype_digit($command[1]) and ctype_digit($command[2])) $gd = resizeandcrop($gd, $command[1], $command[2]);
			elseif ($command[0] == 'rp' and ctype_digit($command[1]) and ctype_digit($command[2])) $gd = resizeandpad($gd, $command[1], $command[2], isset($command[3]) ? $command[3] : 'FFFFFF');
			elseif ($command[0] == 'r' and ctype_digit($command[1]) and ctype_digit($command[2])) $gd = resize($gd, $command[1], $command[2]);
			elseif ($command[0] == 'w' and ctype_digit($command[1])) $gd = resizetowidth($gd, $command[1]);
			elseif ($command[0] == 'h' and ctype_digit($command[1])) $gd = resizetoheight($gd, $command[1]);
			elseif ($command[0] == 'm' and ctype_digit($command[1])) $gd = resizetomax($gd, $command[1]);
			elseif ($command[0] == 'p' and ctype_digit($command[1]) and ctype_digit($command[2]) and ctype_digit($command[3]) and ctype_digit($command[4])) $gd = pad($gd, $command[1], $command[2], $command[3], $command[4], isset($command[5]) ? $command[5] : 'FFFFFF');
		}

		if ($max_dimension and (imagesx($gd) > $max_dimension or imagesy($gd) > $max_dimension)) {
			require '404.php';
		} else {
			@mkdir(dirname($cache_file), 0755, true);
			if ($image['mime_type'] == 'image/jpeg') imagejpeg($gd, $cache_file, $jpeg_quality);
			elseif ($image['mime_type'] == 'image/gif') imagegif($gd, $cache_file);
			elseif ($image['mime_type'] == 'image/png') imagepng($gd, $cache_file, $png_compression);
			header("Content-type: {$image['mime_type']}");
			header("Content-disposition: inline; filename={$image['filename']}");
			readfile($cache_file);
		}
		exit;
	}
	
} else {
	echo "Invalid ID";
}



